/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.ugame.service.client;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import vn.ugame.security.client.Config;
import vn.ugame.security.client.KeyFactory;
import vn.ugame.security.client.RandomString;
import vn.ugame.security.client.Security;

/**
 *
 * @author user
 */
public class ActiveService {

    public String activeApp(String code, String imei) throws Exception {
        String key = RandomString.getInstance().getRandomString(Config.RANDOM_LENGTH);
        String secretKey = KeyFactory.getInstance().createSecretKey(key, getServerTime());

        code = Security.getInstance().encrypt(code, secretKey);
        String service = Security.getInstance().encrypt(Config.ACTIVATE_SERVICE, secretKey);

        // Create a new HttpClient and Post Header
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpClient httpclient = new DefaultHttpClient(params);
        String url = Config.PORT == null ? "http://" + Config.SERVER + "/" + service
                : "http://" + Config.SERVER + ":" + Config.PORT + "/" + service;

        HttpPost httppost = new HttpPost(url);
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("key", key));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("imei", imei));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String message = inputStreamToString(response.getEntity().getContent());
            String decryptedMessage = Security.getInstance().decrypt(message, secretKey);

            return decryptedMessage;
        } else {
            throw new Exception(String.valueOf(response.getStatusLine().getStatusCode()));
        }
    }

    private String getServerTime() throws Exception {
        // Create a new HttpClient and Post Header
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);

        HttpClient httpclient = new DefaultHttpClient(params);
        String url = Config.PORT == null ? "http://" + Config.SERVER + "/" + Config.TIME_SERVICE
                : "http://" + Config.SERVER + ":" + Config.PORT + "/" + Config.TIME_SERVICE;

        HttpPost httppost = new HttpPost(url);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return inputStreamToString(response.getEntity().getContent());
        } else {
            throw new Exception(String.valueOf(response.getStatusLine().getStatusCode()));
        }
    }

    private String inputStreamToString(InputStream is) throws Exception {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        // Return full string
        return total.toString();
    }
}
